<?php

namespace App\Http\Controllers\Admin;

use App\Models\Ranking;
use Illuminate\Http\Request;
use App\Http\Requests\RankingRequest;
use App\Http\Controllers\Controller;

class RankingController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $objectType = $request->object_type;
        $name = $request->name;
        $list = Ranking::when($objectType, function ($query) use ($objectType) {
                $query->where("object_type", $objectType);
            })
            ->when($name, function ($query) use ($name) {
                $query->where("name", "like", "%{$name}%");
            })
            ->paginate(request('per_page', 20));

        return view('admin.ranking.index', compact('list'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $ranking = new Ranking();

        return view('admin.ranking.form', compact('ranking'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(RankingRequest $request)
    {
        $result = Ranking::create($request->all());
        return redirect()->route('admin.ranking.index')->with("success", "创建成功");
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $ranking = Ranking::findOrFail($id);
        return view('admin.ranking.form', compact('ranking'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(RankingRequest $request, $id)
    {
        Ranking::findOrFail($id)->update($request->all());
        return redirect()->route('admin.ranking.index')->with("success", "更新成功");
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        Ranking::findOrFail($id)->delete();
        return back()->with("success", "删除成功");
    }
}
